<template>
  <div class="registerBody">

    <el-row :gutter="20" class="rowEl">
      <el-col :span="7"><div class="grid-content"></div></el-col>
      <el-col :span="10">
        <div class="grid-content bg-purple bodyWidth">
<!--          <h1>用户注册</h1>-->
          <div style="position: center;font-size: 20px;font-weight: 600;">学生注册</div>
          <div class="formContent">
            <el-form ref="userMessageFormRef" :model="userMessageForm" label-width="80px" :rules="formRules">
              <el-form-item label="昵称设置" prop="name">
                <el-input v-model="userMessageForm.name"  size="small" style="width: 300px;"></el-input>
              </el-form-item>
              <div style="display: flex;height: 42px;margin-bottom: 15px">
                <el-form-item label="账号设置" prop="userName">
                  <el-input v-model="userMessageForm.userName" size="small" style="width: 300px;"></el-input>
                </el-form-item>
                <el-button @click="checkId" type="text" style="margin-left: 5px" size="small">检查账号是否可用</el-button>
              </div>
              <el-form-item label="密码" prop="pass">
                <el-input type="password" v-model="userMessageForm.pass" autocomplete="off" size="small" style="width: 300px;"></el-input>
              </el-form-item>
              <el-form-item label="确认密码" prop="checkPass">
                <el-input type="password" v-model="userMessageForm.checkPass" autocomplete="off" size="small" style="width: 300px;"></el-input>
              </el-form-item>
              <div style="display: flex;height: 42px;margin-bottom: 15px">
                <el-form-item label="注册邮箱" prop="userMailbox">
                  <el-input v-model="userMessageForm.userMailbox" size="small" style="width: 300px;"></el-input>
                </el-form-item>
                <el-button @click="sendActiveCode" type="text" style="margin-left: 5px" size="small" :disabled="!getCodeVisible">{{btnString}}</el-button>
              </div>

              <el-form-item label="验证码" prop="activeCode">
                <el-input v-model="userMessageForm.activeCode" autocomplete="off" size="small" style="width: 300px;"></el-input>
              </el-form-item>
              <el-form-item label="性别" prop="userSex">
                <el-radio-group v-model="userMessageForm.userSex">
                  <el-radio label="男"></el-radio>
                  <el-radio label="女"></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="所在省份" prop="userProvince">
                <el-select v-model="userMessageForm.userProvince"  placeholder="请选择省份" @change="selectProvince(userMessageForm.userProvince)" size="small" style="width: 300px;">
                  <el-option v-for="(province,key) in provinces" :label="province.cityName" :key="province.id" :value="province.id" ></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="地级市" prop="userCity">
                <el-select v-model="userMessageForm.userCity" :disabled="cityDisable" placeholder="请选择所在地级市" @change="selectCity(userMessageForm.userCity)" size="small" style="width: 300px;">
                  <el-option v-for="(city,key) in cities" :label="city.cityName" :key="city.id" :value="city.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="县级市/区" prop="userDistrict">
                <el-select v-model="userMessageForm.userDistrict" :disabled="districtDisable" placeholder="请选择所在县" size="small" style="width: 300px;">
                  <el-option v-for="(district,key) in districts" :label="district.cityName" :key="district.id" :value="district.id"></el-option>
                </el-select>
              </el-form-item>
<!--              <el-form-item label="头像上传">-->
<!--                <div>-->
<!--                  <el-upload-->
<!--                          class="avatar-uploader"-->
<!--                          :action="this.$store.state.pictureBaseUrl+'update'"-->
<!--                          :http-request="handleUpload2"-->
<!--                          :show-file-list="false"-->

<!--                          :before-upload="beforeAvatarUpload">-->
<!--                    <img v-if="imageUrl" :src="imageUrl" class="avatar">-->
<!--                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--                  </el-upload>-->
<!--                </div>-->
<!--              </el-form-item>-->
              <el-form-item>
                <el-button type="success" @click="onSubmit">立即注册</el-button>
                <el-button type="info" @click="resetForm">重置</el-button>
                <el-button type="primary" @click="returnLogin">返回登陆页</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-col>
      <el-col :span="7"></el-col>
    </el-row>
  </div>
</template>
<script>
  import qs from 'qs'
  import infoClient from '../../jsDir/aliOss';
  import dateUtil from '../../jsDir/dateUtil'
  export default {
    name: "Registered",
    created() {
      this.getProvinces()
    },
    data() {
      let validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.userMessageForm.checkPass !== '') {
            this.$refs.userMessageFormRef.validateField('checkPass');
          }
          callback();
        }
      };
      let validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.userMessageForm.pass) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        userMessageForm: {
          userNickname: '',
          userPhone: '',
          userSex: '',
          userProvince: '',
          userCity: '',
          userDistrict: '',
          userIcon: '',
          pass: '',
          checkPass: '',
          userMailbox: '',
          activeCode: '',
        },
        cityDisable: true,
        districtDisable: true,
        formRules: {
          pass: [
            {required: true, validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            {required: true, validator: validatePass2, trigger: 'blur' }
          ],
          userNickname: [
            { required: true, message: '请输入设置的昵称', trigger: 'blur' },
            { min: 2, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
          ],
          userPhone: [
            { required: true, message: '请输入设置的账号', trigger: 'blur' },
            { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
          ],
          userSex: [
            { required: true, message: '请输入性别', trigger: 'blur' },
          ],
          userProvince: [
            { required: true, message: '请选择省份', trigger: 'blur' },
          ],
          userCity: [
            { required: true, message: '请选择地级市', trigger: 'blur' },
          ],
          activeCode: [
            { required: true, message: '请输入验证码', trigger: 'blur' },
          ],
          userMailbox:[
            { required: true, message: '请输入邮箱地址', trigger: 'blur' },
            { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
          ]
        },
        provinces: [],
        cities: [],
        districts: [],
        imageUrl: '',
        getCodeVisible: true,
        timeSeconds: 60,
      }
    },
    computed: {
      btnString() {
        if (this.getCodeVisible) {
          return '发送验证码';
        }else {
          return '重新发送 '+this.timeSeconds+'s';
        }
      }
    },
    methods: {
      // handleUpload(file) {
      //   const _file = file.file;
      //   console.log(_file);
      //   let formData = new FormData();
      //   formData.append("file", _file);
      //   this.$http.post('/file/update', formData, {
      //     headers: {
      //       'Content-Type': 'application/form-data'
      //     },
      //   }).then(res => {
      //     this.userMessageForm.userIcon = this.$store.state.pictureBaseUrl+'upload?url='+ res.data.data;
      //     this.imageUrl = this.userMessageForm.userIcon;
      //   }).catch(err => {
      //     console.log("err")
      //   })
      // },
      handleUpload2(file) {
        const _file = file.file;
        console.log(_file)
        console.log('avatar'+dateUtil()+_file.name);
        console.log(infoClient());
        infoClient().multipartUpload('avatar'+dateUtil()+_file.name, _file, {}).then((results) => {
          console.log(results)
          this.imageUrl = results.res.requestUrls[0].split('?')[0];
          this.userMessageForm.userIcon = this.imageUrl;
        }).catch((err) => {
          console.log(err);
        });
      },
      checkId() {
        if (this.userMessageForm.userPhone.length == 0) {
          this.$message.error("账号不能为空");
          return;
        }
        this.$http.get('/user/checkUser',{
          params: {
            userPhone: this.userMessageForm.userPhone
          }
        }).then(res=> {
          if (res.data.successed) {
            this.$message.success('该账号可用');
          }else {
            this.$message.error(res.data.message);
            this.userMessageForm.userPhone = '';
          }
        })
      },
      sendActiveCode() {
        if (this.userMessageForm.userMailbox.length === 0) {
          this.$message.warning('邮箱不能为空');
          return
        }
        this.$http.get('/user/sendEmail',{
          params: {
            userMailbox: this.userMessageForm.userMailbox,
          }
        }).then(res=> {
          if (res.data.successed) {
            this.$message.success('成功发送验证码')
          }else{
            this.$message.error(res.data.message);
            this.userMessageForm.userMailbox = '';
          }

        })
        this.timeDown();
      },
      timeDown() {
        let  num =setInterval(()=> {
          this.getCodeVisible = false;
          this.timeSeconds -=1;
          if (this.timeSeconds < 1) {
            clearInterval(num);
            this.getCodeVisible = true;
            this.timeSeconds = 60;
          }
        },1000)
      },
      selectProvince(province){
        // console.log(shopProvince)
        if (province.length === 0){
          return
        }
        this.getCities(province)
        this.userMessageForm.userCity = '';
        this.userMessageForm.userDistrict= '';
        this.cityDisable = false;
        this.districtDisable = true;
      },
      selectCity(City){
        if (City.length === 0){
          return
        }
        this.getDistrict(City)
        this.userMessageForm.userDistrict= '';
        this.districtDisable = false;
      },
      returnLogin(){
        this.$router.push('/login')
      },
      onSubmit(){
        //表单预校验
        this.$refs.userMessageFormRef.validate(valid =>{
          if(!valid){
            return;
          }else{
            if (this.imageUrl == '') {
              this.$message.error('用户头像不能为空，请上传头像');
              return;
            }
            this.$http.post('/user/registered', qs.stringify(this.userMessageForm)
            ).
            then(res=>{
              console.log(res)
              if (res.data.code !== 200) {
                this.$message.error(res.data.message);
                return
              }
              this.$message.success(res.data.message);
              // this.cities = res.data.data;
              this.$router.push('/login')
            })
          }
        });

      },
      getProvinces() {
        this.$http.get('/city/provinces').then(res=>{
          console.log(res)
          if (res.data.code !== 200) return this.$message.error(res.data.message);
          // this.$message.success(res.data.message);
          this.provinces = res.data.data;
        })
      },
      getCities(item){
        // console.log(item+'getCities')
        this.$http.get('/city/cities',{
            params: {
              pid: item,
            },
        }
        ).then(res=>{
          console.log(res)
          if (res.data.code !== 200) {
            this.$message.error(res.data.message);
            return
          }
          // this.$message.success(res.data.message);
          this.cities = res.data.data;
        })
      },
      getDistrict(item){
        // console.log(item+'getCities')
        this.$http.get('/city/districts',{
              params: {
                pid: item,
              },
            }
        ).then(res=>{
          console.log(res)
          if (res.data.code !== 200) {
            this.$message.error(res.data.message);
            return
          }
          // this.$message.success(res.data.message);
          this.districts = res.data.data;
        })
      },
      resetForm(){
        console.log(this)
        this.$refs.shopMessageFormRef.resetFields();
      },
      // handleAvatarSuccess(res, file) {
      //   // console.log(res.data)
      //   this.imageUrl = URL.createObjectURL(file.raw);
      //   // console.log(this.imageUrl)
      //   this.userMessageForm.userIcon = this.$store.state.pictureBaseUrl+'upload?url='+ res.data;
      // },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      }
    }
  }
</script>

<style Lnag="less" scoped>

  .el-col {
    border-radius: 4px;
  }

  .rowEl{
    height: 900px;
    padding-top: 30px;
  }

  .registerBody{
    background-color: #eeeeee;
    height: 100%;
  }


  .bg-purple {
    background: #ffffff;
    padding: 60px;
    height: 100%;
  }

  .bodyWidth{
    width: 600px;
  }


  .grid-content {
    height: 100%;
    padding-top: 30px;
    border-radius: 4px;
    min-height: 500px;

  }


  .avatar-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 180px;
  }
  .avatar-uploader:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
